package com.wanghua.mall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * RabbitMQ实战应用
 *
 * @author wanghua
 * @create 2021-09-10 13:07
 */
@Configuration
public class WareRabbitMQConfig {

    public static final String STOCK_EVENT_EXCHANGE_NAME = "stock.event.exchange";
    public static final String STOCK_DELAY_QUEUE_NAME = "stock.delay.queue";
    public static final String STOCK_RELEASE_QUEUE_NAME = "stock.release.stock.queue";
    public static final String STOCK_LOCKED_BINDING_NAME = "stock.locked";
    public static final String STOCK_RELEASE_BINDING_NAME = "stock.release.#";

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 死信队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", STOCK_EVENT_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", STOCK_RELEASE_BINDING_NAME);
        arguments.put("x-message-ttl", 60000 * 50); // 消息过期时间 1分钟
        return new Queue(STOCK_DELAY_QUEUE_NAME, true, false, false, arguments);
    }

    /**
     * 死信队列转发的队列，被消费者监听
     *
     * @return
     */
    @Bean
    public Queue stockReleaseQueue() {
        return new Queue(STOCK_RELEASE_QUEUE_NAME, true, false,
                false, null);
    }

    /**
     * 库存服务唯一交换机
     *
     * @return
     */
    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange(STOCK_EVENT_EXCHANGE_NAME, true,
                false, null);
    }

    /**
     * @return
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding(STOCK_DELAY_QUEUE_NAME, Binding.DestinationType.QUEUE,
                STOCK_EVENT_EXCHANGE_NAME, STOCK_LOCKED_BINDING_NAME, null);
    }

    @Bean
    public Binding stockReleaseBinding() {
        return new Binding(STOCK_RELEASE_QUEUE_NAME, Binding.DestinationType.QUEUE,
                STOCK_EVENT_EXCHANGE_NAME, STOCK_RELEASE_BINDING_NAME, null);
    }
}
